package com.helios.core.service;

import java.util.List;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.helios.core.bean.Link;
import com.helios.core.mapper.LinkMapper;
import com.helios.core.util.RedisUtil;

/**
 * 友情链接数据服务.
 * 
 * @author liyu
 */
@Service
public class LinkService extends ServiceAdapter<Link> {

    @Autowired
    private LinkMapper linkMapper;

    @Override
    protected String getDispInfo() {
        return "友情链接";
    }

    @Override
    protected String getCacheKey(Object args) {
        if(args instanceof Link) {
            return "LINK_" + ((Link) args).getId();
        } else {
            return "LINK_" + args.toString();
        }
    }
    
    public Link get(Integer id) {
        return getCache(id, Link.class, (key) -> linkMapper.get(NumberUtils.toInt(key.toString())));
    }
    
    public List<Link> gets() {
        List<Link> lists = RedisUtil.getList("LINK");
        if(lists == null || lists.isEmpty()) {
            lists = linkMapper.gets();
        }
        if(lists != null && lists.isEmpty() == false) {
            RedisUtil.putList("LINK", lists, getCacheTime()); 
        }
        return lists;
    }
    
    public boolean save(Link bean) {
        if(bean == null) return false;
        if(bean.getId() == null || bean.getId() == 0) {
            return linkMapper.insert(bean) == 1;
        } else {
            return updateCache(bean, (obj) -> linkMapper.update(obj) == 1);
        }
    }
    
    public boolean delete(Integer id) {
        return deleteCache(id, (key) -> linkMapper.delete(key) == 1);
    }
}
